package com.funsport.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 邮件发送服务
 *
 * @author Fun-Sport Team
 */
@Slf4j
@Service
public class EmailService {

    @Autowired(required = false)
    private JavaMailSender mailSender;

    @Value("${spring.mail.username:}")
    private String fromEmail;

    @Value("${app.feedback.email:1329090883@qq.com}")
    private String feedbackEmail;

    /**
     * 发送简单文本邮件
     */
    public void sendSimpleEmail(String to, String subject, String content) {
        if (mailSender == null) {
            log.warn("邮件服务未配置，无法发送邮件");
            return;
        }

        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(fromEmail);
            message.setTo(to);
            message.setSubject(subject);
            message.setText(content);
            
            mailSender.send(message);
            log.info("邮件发送成功: to={}, subject={}", to, subject);
        } catch (Exception e) {
            log.error("邮件发送失败: to={}, subject={}", to, subject, e);
        }
    }

    /**
     * 发送HTML邮件
     */
    public void sendHtmlEmail(String to, String subject, String htmlContent) {
        if (mailSender == null) {
            log.warn("邮件服务未配置，无法发送邮件");
            return;
        }

        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
            
            helper.setFrom(fromEmail);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(htmlContent, true);
            
            mailSender.send(message);
            log.info("HTML邮件发送成功: to={}, subject={}", to, subject);
        } catch (Exception e) {
            log.error("HTML邮件发送失败: to={}, subject={}", to, subject, e);
        }
    }

    /**
     * 异步发送用户反馈邮件
     */
    @Async
    public void sendFeedbackEmail(Long userId, String userNickname, String type, 
                                   String content, String contact, String images) {
        if (mailSender == null) {
            log.warn("邮件服务未配置，跳过反馈邮件发送");
            return;
        }

        String subject = "【Fun-Sport】新的用户反馈 - " + getTypeName(type);
        String htmlContent = buildFeedbackHtmlContent(
            userId, userNickname, type, content, contact, images
        );
        
        sendHtmlEmail(feedbackEmail, subject, htmlContent);
    }

    /**
     * 构建反馈邮件HTML内容
     */
    private String buildFeedbackHtmlContent(Long userId, String userNickname, String type, 
                                            String content, String contact, String images) {
        StringBuilder html = new StringBuilder();
        html.append("<!DOCTYPE html>");
        html.append("<html>");
        html.append("<head>");
        html.append("<meta charset='UTF-8'>");
        html.append("<style>");
        html.append("body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }");
        html.append(".container { max-width: 600px; margin: 20px auto; padding: 20px; ");
        html.append("border: 1px solid #ddd; border-radius: 8px; background: #f9f9f9; }");
        html.append(".header { background: linear-gradient(135deg, #FF6B6B 0%, #FF8E53 100%); ");
        html.append("color: white; padding: 20px; border-radius: 8px 8px 0 0; text-align: center; }");
        html.append(".content { background: white; padding: 20px; margin-top: 20px; border-radius: 8px; }");
        html.append(".field { margin-bottom: 15px; }");
        html.append(".label { font-weight: bold; color: #FF6B6B; }");
        html.append(".value { margin-top: 5px; padding: 10px; background: #f5f5f5; ");
        html.append("border-left: 3px solid #FF6B6B; white-space: pre-wrap; }");
        html.append(".footer { margin-top: 20px; padding-top: 20px; border-top: 1px solid #ddd; ");
        html.append("text-align: center; color: #999; font-size: 12px; }");
        html.append("</style>");
        html.append("</head>");
        html.append("<body>");
        html.append("<div class='container'>");
        
        // 头部
        html.append("<div class='header'>");
        html.append("<h2>📬 新的用户反馈</h2>");
        html.append("<p>Fun-Sport 运动社交平台</p>");
        html.append("</div>");
        
        // 内容
        html.append("<div class='content'>");
        
        // 反馈类型
        html.append("<div class='field'>");
        html.append("<div class='label'>反馈类型</div>");
        html.append("<div class='value'>").append(getTypeIcon(type)).append(" ")
            .append(getTypeName(type)).append("</div>");
        html.append("</div>");
        
        // 用户信息
        html.append("<div class='field'>");
        html.append("<div class='label'>用户信息</div>");
        html.append("<div class='value'>");
        html.append("用户ID: ").append(userId).append("<br>");
        html.append("昵称: ").append(userNickname != null ? userNickname : "未设置");
        html.append("</div>");
        html.append("</div>");
        
        // 反馈内容
        html.append("<div class='field'>");
        html.append("<div class='label'>详细描述</div>");
        html.append("<div class='value'>").append(escapeHtml(content)).append("</div>");
        html.append("</div>");
        
        // 联系方式
        if (contact != null && !contact.trim().isEmpty()) {
            html.append("<div class='field'>");
            html.append("<div class='label'>联系方式</div>");
            html.append("<div class='value'>").append(escapeHtml(contact)).append("</div>");
            html.append("</div>");
        }
        
        // 图片附件
        if (images != null && !images.trim().isEmpty()) {
            String[] imageArray = images.split(",");
            html.append("<div class='field'>");
            html.append("<div class='label'>相关截图 (").append(imageArray.length).append("张)</div>");
            html.append("<div class='value'>");
            for (int i = 0; i < imageArray.length; i++) {
                html.append("图片").append(i + 1).append(": ")
                    .append("<a href='").append(imageArray[i]).append("' target='_blank'>")
                    .append("查看图片").append("</a><br>");
            }
            html.append("</div>");
            html.append("</div>");
        }
        
        // 提交时间
        html.append("<div class='field'>");
        html.append("<div class='label'>提交时间</div>");
        html.append("<div class='value'>")
            .append(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
            .append("</div>");
        html.append("</div>");
        
        html.append("</div>");
        
        // 页脚
        html.append("<div class='footer'>");
        html.append("<p>此邮件由 Fun-Sport 系统自动发送，请勿直接回复</p>");
        html.append("<p>收到反馈后请及时处理并在管理后台进行回复</p>");
        html.append("</div>");
        
        html.append("</div>");
        html.append("</body>");
        html.append("</html>");
        
        return html.toString();
    }

    /**
     * 获取反馈类型名称
     */
    private String getTypeName(String type) {
        switch (type) {
            case "bug": return "Bug反馈";
            case "feature": return "功能建议";
            case "ui": return "UI优化";
            case "other": return "其他反馈";
            default: return "未知类型";
        }
    }

    /**
     * 获取反馈类型图标
     */
    private String getTypeIcon(String type) {
        switch (type) {
            case "bug": return "🐛";
            case "feature": return "💡";
            case "ui": return "🎨";
            case "other": return "📝";
            default: return "📬";
        }
    }

    /**
     * HTML转义
     */
    private String escapeHtml(String text) {
        if (text == null) {
            return "";
        }
        return text.replace("&", "&amp;")
                   .replace("<", "&lt;")
                   .replace(">", "&gt;")
                   .replace("\"", "&quot;")
                   .replace("'", "&#x27;")
                   .replace("\n", "<br>");
    }
}

